package www.hz.domain.strategy.service.rule.tree.factory.engine.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import www.hz.domain.strategy.model.valobj.*;
import www.hz.domain.strategy.service.rule.tree.ILogicTreeNode;
import www.hz.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import www.hz.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;

import java.util.List;
import java.util.Map;

/**
 * @className: DecisionTreeEngine
 * @Description: 决策树引擎
 * @version: v1.８.0
 * @author: hz
 * @date: 2025/3/17 20:54
 */
public class DecisionTreeEngine implements IDecisionTreeEngine {
    private final Map<String, ILogicTreeNode> logicTreeNodeGroup;
    private final RuleTreeVO ruleTreeVO;

    public DecisionTreeEngine(Map<String, ILogicTreeNode> logicTreeNodeGroup,RuleTreeVO ruleTreeVO) {
        this.logicTreeNodeGroup = logicTreeNodeGroup;
        this.ruleTreeVO=ruleTreeVO;
    }

    @Override
    public DefaultTreeFactory.StrategyAwardVO process(String userId, Long strategyId, Integer awardId) {
        DefaultTreeFactory.StrategyAwardVO strategyAwardData = null;
        //获取基础信息
        String nextNode = ruleTreeVO.getTreeRootRuleNode();
        Map<String, RuleTreeNodeVO> treeNodeMap = ruleTreeVO.getTreeNodeMap();
        //获取起始节点（根节点记录了第一个要执行的规则）
       while (!StringUtils.isBlank(nextNode)){
           RuleTreeNodeVO ruleTreeNodeVO = treeNodeMap.get(nextNode);
           ILogicTreeNode logicTreeNode = logicTreeNodeGroup.get(ruleTreeNodeVO.getRuleKey());
           DefaultTreeFactory.TreeActionEntity actionEntity = logicTreeNode.logic(userId, strategyId, awardId);
           RuleLogicCheckTypeVO ruleLogicCheckType = actionEntity.getRuleLogicCheckType();
            strategyAwardData = actionEntity.getStrategyAwardData();
           List<RuleTreeNodeLineVO> treeNodeLineVOList = ruleTreeNodeVO.getTreeNodeLineVOList();
           nextNode=nextNode(ruleLogicCheckType,treeNodeLineVOList);
       }



        return strategyAwardData;

    }

    public String  nextNode(RuleLogicCheckTypeVO ruleLogicCheckType, List<RuleTreeNodeLineVO> treeNodeLineVOList) {
        if (null == treeNodeLineVOList || treeNodeLineVOList.isEmpty()) return null;
        for (RuleTreeNodeLineVO  ruleTreeNodeLineVO : treeNodeLineVOList){
            if (decisionLogic(ruleLogicCheckType.getCode(),ruleTreeNodeLineVO)) return ruleTreeNodeLineVO.getRuleNodeTo();
        }
        return null;
    }


    public boolean decisionLogic(String matterValue, RuleTreeNodeLineVO nodeLine) {
        switch (nodeLine.getRuleLimitType()) {
            case EQUAL:
                return matterValue.equals(nodeLine.getRuleLimitValue().getCode());
            // 以下规则暂时不需要实现
            case GT:
            case LT:
            case GE:
            case LE:
            default:
                return false;
        }
    }
}